import java.util.*; 
import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Vector;
import java.io.*;

/**
Deck extends Cardset and has additional contructors to allow loading of cards from files.
*/
public class Deck extends CardSet {
	
	private Table table;
	
	public static final String DECK_PATH = "decks/";
	public static final String DECK_EXTENSION = ".deck";
	
	public Deck() {
		super();
	}
	
	public Deck(int numCards) {
		this();
		
		for(int i = 0; i < numCards; i++) {
			super.add(new Card(i));
		}
	}
	
	public Deck(String deckname) {
		this( new File(DECK_PATH + deckname + "/" + deckname) );
	}
	
	public Deck(File deckfile) {
		
		this();
		String deckName = deckfile.getName();
		String p = DECK_PATH + deckName.substring(0, deckName.lastIndexOf(".")) + "/" + deckName;
		System.out.println("PATH: " + p);
		String line = "";
		String[] args;
		HashMap<String, String> backs = new HashMap<String, String>();
		Vector<Card> tmpCards = new Vector<Card>();
		String name, back, image;
		int cardId = 0;
		
		try {
			//String p = deckfile.getPath();
			p = p.replace('\\', '/');
			Dbg.println("Deck Path: " + p);
			InputStream is = getClass().getResourceAsStream(p);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String imgPath = p.substring(0, p.lastIndexOf('/'));
			Dbg.println(imgPath);
			//read a line at a time
			while((line = br.readLine()) != null) {
				args = line.split(",");
				
				//get card backs
				if(args[0].equalsIgnoreCase("back")) {
					backs.put(args[1], imgPath + "/" + args[2]);
				//get card data
				} else if (args[0].equalsIgnoreCase("card")) {
					name = args[1];
					back = args[2];
					image = imgPath + "/" + args[3];
					Card newCard = new Card(cardId, image, backs.get(back), name);
						
					//get attributes
					for (int i = 4; i < args.length; i += 2) {
						newCard.addAttribute(args[i], args[i+1]);
					}
					
					tmpCards.add(newCard);
					cardId++;
				}
			}
			
			super.addAll(tmpCards);
			/*
			CardsServer.setSnapX(cards.get(0).getRectangle().width);
			CardsServer.setSnapY(cards.get(0).getRectangle().height);
			*/
			//TODO 
			
		} catch (IOException e) {
			System.err.println("IO problems");
			e.printStackTrace();
		}
	}
	
}
